package com.hk.webapp.filter;

import com.hk.webapp.custom.CustomMultipartHttpServletRequest;
import com.hk.webapp.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * (C) Copyright 2017-now
 * All rights reserved.
 * <p>
 * 自定义过滤器
 *
 * @author DreamerCK
 * @date 2019-01-11 12:34
 **/
@Slf4j
@WebFilter(filterName = "customFilter", urlPatterns = {"/api/*"})
public class CustomFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //在filter中可以注入service
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        // If the Http request is OPTIONS then just return the status code 200
        // which is HttpServletResponse.SC_OK in this code
        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(req, res);
        }
        // Except OPTIONS, other request change to CustomHttpServletRequest
        else {
            if (Optional.ofNullable(request.getContentType()).orElse(StringUtils.EMPTY).contains(ContentType.MULTIPART_FORM_DATA.getMimeType())) {
                request = new CustomMultipartHttpServletRequest(request);
                chain.doFilter(request, res);
            } else {
                request = new JwtUtil.CustomHttpServletRequest(request);
                chain.doFilter(request, res);
            }
        }
    }

    @Override
    public void destroy() {

    }


}
